
package com.heiyu.utils;

import com.google.common.base.Joiner;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author by jiuru on 2017/2/14.
 */
public class QiniuUtils {

    private static Logger logger = LoggerFactory.getLogger(QiniuUtils.class);


    static String[] SUFFIX_ARRAY = new String[]{".jpg", ".jpeg", ".gif", ".png", ".bmp", ".js", ".css", ".less"};

    //设置好账号的ACCESS_KEY和SECRET_KEY
    static String ACCESS_KEY = "MgJbJZM4Wp6I6NucZZgbwBoDVQqRWttbMK_D87Ar";

    static String SECRET_KEY = "EUUqwtwxl-UAccFPzxlDMtmjKdLvenpo9kdGBgQF";

    //要上传的空间
    static String BUCKET_NAME = "tiantaishan";

    static String QINIU_URL = "http://op85qdkke.bkt.clouddn.com";

    //密钥配置
    static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);


    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public static String getUpToken() {
        return auth.uploadToken(BUCKET_NAME);
    }

    public static String upload(MultipartFile file) throws IOException {
        Zone z = Zone.autoZone();
        Configuration c = new Configuration(z);
        UploadManager uploadManager = new UploadManager(c);
        try {
            String fileName = StringUtils.lowerCase(file.getOriginalFilename());
            if (!StringUtils.endsWithAny(fileName, SUFFIX_ARRAY)) {
                throw new RuntimeException("文件格式错误");
            }
            String[] fileNameArray = StringUtils.split(fileName, ".");
            String suffix = fileNameArray[fileNameArray.length - 1];
            fileName = Joiner.on(".").join(System.currentTimeMillis(), suffix);
            //调用put方法上传
            Response res = uploadManager.put(file.getBytes(), fileName, getUpToken());

            //打印返回的信息
            logger.info(res.bodyString());
            return QINIU_URL + "/" + fileName;
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            logger.error(r.toString());
            try {
                //响应的文本信息
                logger.error(r.bodyString());
            } catch (QiniuException e1) {
                //ignore
                logger.error(e1.getMessage(), e1);
            }
        }
        return null;
    }


}
